
import './index.css'
import axios from "@/utils/request.js";
import '@/utils/auth.js'
import editor from '@/utils/editor.js'
import serialize from '/node_modules/form-serialize';
(()=>{
axios({
  url: '/v1_0/channels'
})
  .then((res) => {
    document.querySelector('.channel_id').innerHTML =
      `<option value="">请选择文章频道</option>` +
      res.data.channels
        .map(
          (item) => `
    <option value="${item.id}">${item.name}</option>
  `
        )
        .join('')
  })
  .catch((err) => {})
})()
;( ()=>{
  // console.log(location.search);
  let urlQueryStr = new URLSearchParams(location.search)
  // console.log(urlQueryStr.toString());

  urlQueryStr.forEach(async (value, key) => {
    if (key == 'id') {
      try {
        
        //发送编辑请求
        const res = await axios({
          url: `/v1_0/mp/articles/${value}`
        })
        document.querySelector('.card-header').innerHTML = '修改文章'
        document.querySelector('.btn').innerHTML = '修改'

        const obj = {
          id: res.data.id,
          title: res.data.title,
          channel_id: res.data.channel_id,
          content: res.data.content,
          cover: res.data.cover.images[0]
        }

        const keys = Object.keys(obj)
        keys.forEach(key=>{
          if (key == 'content'){
            editor.setHtml(obj[key])
            document.querySelector('.content').value = editor.getHtml()
          }
          else if (key == 'cover'){
            document.querySelector('.rounded').src = obj[key]
            document.querySelector('.place').style.display = 'none'
            document.querySelector('.rounded').style.display = 'block'
          }
          else {
            document.querySelector(`.${key}`).value = obj[key]
          }
        })

        
      } catch (error) {
        console.log(error.message)
      }
      
    }
  })
})()



//上传图片，注意，只有change，图片改变了才会生效，而不是点击的一瞬间
document.querySelector('.cover').onchange = async e =>{
  let fd = new FormData()
  console.dir(e.target.files[0])
  fd.append('image',e.target.files[0])
  if (!e.target.files[0]){
    return
  }
  try {
     const res = await axios({
       url: '/v1_0/upload',
       method: 'POST',
       data: fd
     })

       console.log(res);
       document.querySelector('.rounded').src = res.data.url
       document.querySelector('.place').style.display = 'none'
       document.querySelector('.rounded').style.display = 'block'

  } catch (error) {
    console.log(error.message);
  }
}

document.querySelector('.rounded').onclick = () => {
  document.querySelector('.cover').click()
}


//发布文章
document.querySelector('.btn').onclick = async (e)=>{
  e.preventDefault()
   const id = document.querySelector('.id').value
   id || document.querySelector('.id').removeAttribute('name') 
   const form = document.querySelector('.article-form')
   const data = serialize(form, { hash: true, empty: true })
   const img = document.querySelector('.rounded').src
   data.cover = {
     type: img == '' ? 0 : 1,
     images: [img]
   }
   data.channel_id = parseInt(data.channel_id)
   data.content = editor.getHtml()
   console.log(data);

    //修改
    let method = id ? 'PUT':'POST'
    let msg = id ? '修改' : '发布'  
    let url = id ? `/v1_0/mp/articles/${id}`:'/v1_0/mp/articles'
     console.log(method,msg);
     try {
       const res = await axios({
         url,
         method,
         data
       })
       alert(`${msg}成功`)
       form.reset()
       editor.setHtml('')
       setTimeout(()=>{
          location.href = '../content/content.html'
       },1000)
     } catch (error) {
      console.log(error.message)
     }
  

}